<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="采购订单" prop="pomainId">
        <el-select v-model="formData.pomainId" placeholder="请选择"  @change="handlePomainChange()" filterable :disabled="formData.isDisabled">
        <el-option
            v-for="item in pomainList"
            :key="item.id"
            :label="item.code"
            :value="item.id"
        />
      </el-select>
      </el-form-item> 
      </el-col>
      <el-col :span="8">
        <el-form-item label="业务员" prop="cpersonId">
        <el-select v-model="formData.cpersonId" placeholder="请选择" filterable :disabled="true">
        <el-option
            v-for="item in personList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>
      </el-form-item> 
      </el-col>
      <el-col :span="8">
        <el-form-item label="部门" prop="cdepId">
        <el-tree-select
              v-model="formData.cdepId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id" 
              placeholder="请选择部门"
              filterable 
              :disabled="true"
            />
      </el-form-item>
      </el-col>
      </el-row>

      <el-row :gutter="20">
      <el-col :span="8">
        
      <el-form-item label="供应商" prop="cvenId">
        <el-select v-model="formData.cvenId"  placeholder="请选择"  filterable   :disabled="true">
              <el-option
                v-for="item in vendorList"
                :key="item.id"
                :label="item.name"
                :value="item.id!"
              />
            </el-select>
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="仓库" prop="cwhId">
          <el-select v-model="formData.cwhId" placeholder="请选择" filterable :disabled="formData.isDisabled">
        <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        />
      </el-select>      
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="入库日期" prop="ddate">
        <el-date-picker
          v-model="formData.ddate"
          type="date"
          value-format="x"
          placeholder="选择订单日期"
          :disabled="formData.isDisabled"
          class="!w-100%"
        />
      </el-form-item>
      </el-col>
      </el-row>

      <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="备注" prop="cmemo">
        <el-input v-model="formData.cmemo" placeholder="请输入备注" :disabled="formData.isDisabled"/>
      </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item label="流水号" prop="code">
        <el-input v-model="formData.code" placeholder="自动生成" :disabled="true"/>
      </el-form-item>
      </el-col>
      </el-row>


    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="采购入库子" name="rdrecords01">
        <Rdrecords01Form ref="rdrecords01FormRef" :pid="formData.id" :pomainId="formData.pomainId" :isDisabled="formData.isDisabled"/>
      </el-tab-pane>
    </el-tabs>
    
    <div class="footer">
      <el-button @click="submitForm" type="primary" :isDisabled="formData.isDisabled"  :disabled="formLoading|| route.query.type === 'select'" >确 定</el-button>
      <el-button @click="goBack" >取 消</el-button>
    </div>
      
  </div>
</template>
<script setup lang="ts" >
import { Rdrecord01Api, Rdrecord01VO } from '@/api/wms/rdrecord01';
import Rdrecords01Form from './components/Rdrecords01Form.vue';

import {  VendorVO,getSimpleVendorList } from '@/api/wms/vendor';
import * as UserApi from '@/api/system/user';
import { useRoute, useRouter } from 'vue-router'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { PomainApi, PomainVO } from '@/api/wms/pomain';
import { PersonApi, PersonVO } from '@/api/wms/person'
import { WarehouseApi, WarehouseVO } from '@/api/wms/warehouse'
import { defaultProps, handleTree } from '@/utils/tree';
import { getSimpleDeptList } from '@/api/system/dept';
import { useTagsViewStore } from '@/store/modules/tagsView'

defineOptions({
    name: 'rdrecord01FormCreate'
})
/** 采购入库主 表单 */
// defineOptions({ name: 'Rdrecord01Form' })
const { push, currentRoute } = useRouter() 

const { t } = useI18n() // 国际化
const route = useRoute()
const router = useRouter()
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  cpersonId: undefined,
  cdepId: undefined,
  cvenId: undefined,
  cwhId: undefined,
  ddate: new Date().getTime(),
  cmemo: undefined,
  isDisabled:false,
  pomainId: undefined
})
const formRules = reactive({
  
  pomainId: [{ required: true, message: '采购订单不能为空', trigger: 'blur' }],

  cpersonId: [{ required: true, message: '业务员不能为空', trigger: 'blur' }],
  cdepId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  cvenId: [{ required: true, message: '供应商不能为空', trigger: 'blur' }],
  cwhId: [{ required: true, message: '仓库不能为空', trigger: 'blur' }],

  ddate: [{ required: true, message: '入库日期不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('rdrecords01')
const rdrecords01FormRef = ref()
const personList = ref([] as PersonVO[]) // 
const vendorList = ref([] as VendorVO[]) // 
const deptList = ref<Tree[]>([]) // 树形结构
const pomainList = ref([] as PomainVO[]) // 
const warehouseList = ref([] as WarehouseVO[]) // 
const { delView } = useTagsViewStore() // 视图操作
const pomainsList = ref([] as PomainsVO[]);

const formDataPomain = ref({
  id: undefined,
  code: undefined,
  cpersonId: undefined,
  cdepId: undefined,
  cvenId: undefined,
  ddate: undefined,
  cmemo: undefined,
  checkTime: undefined,
  checkBy: undefined,
  cpersonIds: [],
  cvenIds: [],
  isDisabled:false
});

//加载数据
onMounted(async () => {
    //加载人员数据
    personList.value = await PersonApi.getPersonSimpleList()
  //加载部门树
  deptList.value = handleTree(await getSimpleDeptList())
  //加载供应商
  vendorList.value = await getSimpleVendorList()

  warehouseList.value= await WarehouseApi.getWarehouseSimpleList()
  const pomain = { status: 5 }
    pomainList.value = await PomainApi.getPomainList(pomain)
  initFormData(route.query.id ? String(route.query.id) : undefined)

})


/** 初始化表单数据 */
const initFormData = async (id?: string) => {
  console.log('初始化'+route.query.id)
  if (id) {
    formLoading.value = true
    try {
      console.log('查询数据')
      formData.value = await Rdrecord01Api.getRdrecord01(id)
      if(route.query.type=='select')
      {
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }else if(route.query.type=='update'){
        formData.value.isDisabled = false; // 修改时可以编辑
      formType.value = 'update';
      }else if(route.query.type=='create'){
      // formData.value.isDisabled = false; // 新增时可以编辑
      formType.value = 'create';
      resetForm();
      }else{
        formData.value.isDisabled = true; // 查看时不可以编辑
      formType.value = 'select';
      }
    } finally {
      formLoading.value = false
    }
  } else {
    resetForm()
    formData.value.isDisabled = false; // 创建时可以编辑
    formType.value = 'create'
  }
}




/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await rdrecords01FormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'rdrecords01'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Rdrecord01VO
    // 拼接子表的数据
    data.rdrecords01s = rdrecords01FormRef.value.getData()
    if (formType.value === 'create') {
      await Rdrecord01Api.createRdrecord01(data)
      ElMessage.success(t('common.createSuccess'))
    } else {
      await Rdrecord01Api.updateRdrecord01(data)
      ElMessage.success(t('common.updateSuccess'))
    }
     delView(unref(currentRoute))
    push('/store/rdrecord01')
  } finally {
    formLoading.value = false
  }
}

/** 返回上一页 */
const goBack = () => {
  router.go(-1)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    cpersonId: undefined,
    cdepId: undefined,
    cvenId: undefined,
    cwhId: undefined,
    ddate: new Date().getTime(),
    cmemo: undefined,
  }
  formRef.value?.resetFields()
}


const handlePomainChange = async () => {
  formDataPomain.value = await PomainApi.getPomain(formData.value.pomainId);
    formData.value.cpersonId =formDataPomain.value.cpersonId;
    formData.value.cdepId =formDataPomain.value.cdepId;
    formData.value.cvenId = formDataPomain.value.cvenId;
};

</script>

<style scoped>
.footer {
  margin-top: 20px;
  text-align: right;
}
</style>